package com.infindo.frame.data.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

//import android.util.Log;

import android.content.Context;
import android.util.Log;
 
import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;
import com.tiantian.app.manager.Const;

 

public class RequestGet extends DataHandler {

	private static final String ENCODE = "UTF-8";

	private String url;
 
	private int position;
	private DataProcessor dataProc;
	private String type;
	private Context context;
 

	public RequestGet(Context context,String url,String type,int position, 
			boolean isNeedTimer, DataProcessor dataProc, int dataHandlerNo,
			CallbackListener listener) {
		super(dataHandlerNo, listener);
		this.setBolNeedTimer(isNeedTimer);
		this.url = url;
        this.context = context;
		this.position = position;
		this.type = type;
		this.dataProc = dataProc;
	}

	public void start() {
		new Thread(this).start();
	}

	public void run() {
		Object result = null;
		try {
			result =    new JSONObject(get(url));//for remote data
//			result =  new JSONObject(readJsonFile("rest/"+type+".json"));//for local data
		} catch (Throwable e) {
			result = e;
		}
		if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo())) {
			this.getCallbackListener().callback(type,position,result);
		}
	}
	
	private String readJsonFile(String fileName){
		StringBuffer strBuf = new StringBuffer();
		try{
			InputStream is = context.getAssets().open(fileName);
			InputStreamReader isr = new InputStreamReader(is, ENCODE);
			BufferedReader br = new BufferedReader(isr);
			int ch;
			while((ch=br.read())!=-1){
				strBuf.append((char)ch);
			}
			is.close();
		}catch(IOException e){
			
		}
		return strBuf.toString();
	}
	
 
	
 

	public String get(String url) {
		
//        Log.v("url", ""+url);
		InputStream in = null;
		OutputStream out = null;
		ByteArrayOutputStream bos = null;
		try {
 
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					Const.CONNECT_HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams,
					Const.CONNECT_SOCKET_TIMEOUT);
			hc = new DefaultHttpClient(httpParams);

			HttpGet httpGet = new HttpGet(url);
 
//			if (DataModel.getSessionId() != null
//					&& !"".equals(DataModel.getSessionId().trim())) {
//				httpGet.addHeader("Cookie", "JSESSIONID="
//						+ DataModel.getSessionId());
//			}
 
 

			HttpResponse response = hc.execute(httpGet);
			HttpEntity entity = response.getEntity();
			
//			Log.v("code", ""+response.getStatusLine().getStatusCode());
			
//            if(DataModel.getSessionId()==null || "".equals(DataModel.getSessionId().trim())){
//					Header[] headers = response.getHeaders("Set-Cookie");
//					if(headers != null){
//						int size = headers.length;
//						for(int i=0;i<size;i++){
//							Log.v("Cookie", headers[i].getName()+":"+headers[i].getValue());
//							if(headers[i].getValue().indexOf("JSESSIONID=")!= -1){
//								String cookie = headers[i].getValue();
//								int site = cookie.indexOf(";");
//								if(site>11)
//									cookie = cookie.substring(11, site);
//								else
//									cookie = cookie.substring(0, site);
//								DataModel.setSessionId(cookie);
//							}
//						}
//					}
//            }
//            Log.v("Cookie", ""+DataModel.getSessionId());

			StringBuffer strBuf = new StringBuffer();
			if (entity != null) {
				InputStream is = entity.getContent();
				InputStreamReader isr = new InputStreamReader(is, ENCODE);
				BufferedReader br = new BufferedReader(isr);
				 
				String line;
				while ((line = br.readLine()) != null) {
					strBuf.append(line);
				}
 
				is.close();
 
				entity.consumeContent();

			}
			hc.getConnectionManager().shutdown();
		    if(strBuf.toString() == null || "".equals(strBuf.toString()))
		    	return null;
			try {
//				Log.i("msg", ":@"+strBuf.toString());
				 return strBuf.toString();
			} catch (Exception e) {
//				Log.v("netjsonerr", ""+e.getMessage());
			}
			
 
		} catch (SecurityException se) {
		} catch (InterruptedIOException ie) {
//			System.out.println(ie.getMessage());
		} catch (IOException e) {
//			System.out.println("ioe:" + e.getMessage());
		} catch (NullPointerException ne) {

		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				if (bos != null)
					bos.close();
				if (hc != null){
					hc.getConnectionManager().closeExpiredConnections();
					hc.getConnectionManager().shutdown();
					hc = null;
				}
				this.stopConnect();
			} catch (IOException ignored) {
				this.stopConnect();
			}
		}
		return null;
	}

	public static byte[] convertUnicode2UTF8Byte(String s) {
		byte b[];
		byte b1[];
		int len;
		int count = 0;
		char c;
		if (s == null || s.length() == 0)
			return null;
		len = s.length();
		b = new byte[len * 3];
		for (int i = 0; i < len; i++) {
			c = s.charAt(i);
			if (0x0080 > c) {
				b[count++] = (byte) c;
			} else if (0x0800 > c) {
				b[count++] = (byte) ((c >> 6) | 0xc0);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			} else {
				b[count++] = (byte) ((c >> 12) | 0xE0);
				b[count++] = (byte) (((c & 0x0FC0) >> 6) | 0x80);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			}
		}
		b1 = new byte[count];
		System.arraycopy(b, 0, b1, 0, count);
		b = null;
		return b1;
	}

	/**
	 * Method description
	 * 
	 */
	public static String convertByteArray2UTF8String(byte[] arrays) {
		if (arrays == null)
			return null;
		ByteArrayInputStream bais = new ByteArrayInputStream(arrays, 0,
				arrays.length);
		InputStreamReader isreader = null;

		try {
			isreader = new InputStreamReader(bais, "UTF-8");
		} catch (IOException ioe) {

		} catch (Exception exception1) {
			isreader = new InputStreamReader(bais);
		}
		String s;
		StringBuffer stringbuffer = new StringBuffer();
		int i = -1;
		do {
			try {
				if ((i = isreader.read()) == -1) {
					break;
				}
				char c = (char) i;
				if (c == '\n') {
					break;
				}
				if (c != '\r') {
					stringbuffer.append(c);
				}
				continue;
			} catch (IOException ioe) {

			} catch (Exception exception) {

			}
			break;
		} while (true);
		s = stringbuffer.toString();
		{
			try {
				if (isreader != null) {
					isreader.close();
					isreader = null;
				}
				if (bais != null) {
					bais.close();
					bais = null;
				}
			} catch (Exception exception3) {
			}
		}
		if (s.length() == 0) {
			if (i == -1) {
				return null;
			} else {
				return "";
			}
		} else {
			return s;
		}
	}

//	private byte[] addCapacity(byte rece[]) {
//		byte temp[] = new byte[rece.length + 1024];
//		System.arraycopy(rece, 0, temp, 0, rece.length);
//		return temp;
//	}

}
